package com.zxk.crawler.task;

import com.zxk.core.common.model.FundAnalysise;
import com.zxk.crawler.feign.FundFeignService;
import com.zxk.crawler.pipeline.FundAnalysisePipeline;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.scheduler.BloomFilterDuplicateRemover;
import us.codecraft.webmagic.scheduler.QueueScheduler;
import us.codecraft.webmagic.selector.Selectable;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class FundAnalysiseProcessor implements PageProcessor {

    @Autowired
    private FundAnalysisePipeline fundAnalysisePipeline;

    @Autowired
    private FundFeignService fundService;

    private File file = new File("D:\\file\\zxk\\gogog\\fund.txt");

    @Override
    public void process(Page page) {
        save(page);
    }

    private void save(Page page) {
        Selectable mainContent = page.getHtml().css("#body > div:nth-child(11) > div > div > div.fundDetail-main > div.fundInfoItem > div.dataOfFund");
        Selectable otherContent = page.getHtml().css("#increaseAmount_stage > table > tbody");

        FundAnalysise fundAnalysise = new FundAnalysise();
        //基金名称
        String fundName = page.getHtml().css("#body > div:nth-child(11) > div > div > div.fundDetail-header > div.fundDetail-tit > div","text").toString();
        fundAnalysise.setFundName(fundName);
        //基金代码
        String fundCode = page.getHtml().css("#body > div:nth-child(11) > div > div > div.fundDetail-header > div.fundDetail-tit > div > span.ui-num","text").toString();
        fundAnalysise.setFundCode(fundCode);

        //累计净值
        String fundWorth = mainContent.css("dl.dataItem03 > dd.dataNums > span","text").toString();
        fundAnalysise.setFundWorth(fundWorth);

        //今日收益
        String currentIncome = mainContent.css("dl.dataItem02 > dd.dataNums > span.ui-font-middle.ui-color-red.ui-num", "text").toString();
        String currentNegativeIncome = mainContent.css("dl.dataItem02 > dd.dataNums > span.ui-font-middle.ui-color-green.ui-num", "text").toString();

        fundAnalysise.setCurrentIncome(currentIncome);
        if(currentIncome == null) {
            fundAnalysise.setCurrentIncome(currentNegativeIncome);
        }
        try {
            FileUtils.writeStringToFile(file,fundName+":"+fundCode+":"+fundAnalysise.getCurrentIncome()+"\r\n",true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("fundName"+fundName+":fundCode:"+fundCode+";currentIncome:"+fundAnalysise.getCurrentIncome());
        try {
            String str = FileUtils.readFileToString(new File("D:\\file\\zxk\\gogog\\测试1.txt"));
            str = str + "fundName"+fundName+":fundCode:"+fundCode+";currentIncome:"+fundAnalysise.getCurrentIncome();
            FileUtils.writeStringToFile(new File("D:\\file\\zxk\\gogog\\测试1.txt"),str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //当前值
        String currentValuation = mainContent.css("dl.dataItem02 > dd.dataNums > span.ui-font-large.ui-color-red.ui-num", "text").toString();
        String currentNegativeValuation = mainContent.css("dl.dataItem02 > dd.dataNums > span.ui-font-large.ui-color-green.ui-num", "text").toString();
        fundAnalysise.setCurrentValuation(currentValuation);
        if(currentIncome == null) {
            fundAnalysise.setCurrentValuation(currentNegativeValuation);
        }
        log.info("currentValuation"+fundAnalysise.getCurrentValuation());
        //净值估算
        String fundValuation = mainContent.css("#gz_gsz","text").toString();
        fundAnalysise.setFundValuation(fundValuation);
        //近1月
        String oneMonthIncome;
        oneMonthIncome = mainContent.css("dl.dataItem01 > dd:nth-child(3) > span.ui-font-middle.ui-color-green.ui-num","text").toString();
        if(null == oneMonthIncome || oneMonthIncome.length() == 0) {
            oneMonthIncome = mainContent.css("dl.dataItem01 > dd:nth-child(3) > span.ui-font-middle.ui-color-red.ui-num","text").toString();
        }
        fundAnalysise.setOneMonthIncome(oneMonthIncome);
        //近3月

        String threeMonthIncome = mainContent.css("dl.dataItem02 > dd:nth-child(3) > span.ui-font-middle.ui-color-red.ui-num","text").toString();
        if(null == threeMonthIncome || threeMonthIncome.length() == 0) {
            threeMonthIncome = mainContent.css("dl.dataItem02 > dd:nth-child(3) > span.ui-font-middle.ui-color-green.ui-num","text").toString();
        }
        fundAnalysise.setThreeMonthIncome(threeMonthIncome);
        //近6月
        String sixMonthIncome = mainContent.css("dl.dataItem03 > dd:nth-child(3) > span.ui-font-middle.ui-color-red.ui-num","text").toString();
        if(null == sixMonthIncome || sixMonthIncome.length() == 0) {
            sixMonthIncome = mainContent.css("dl.dataItem03 > dd:nth-child(3) > span.ui-font-middle.ui-color-green.ui-num","text").toString();
        }
        fundAnalysise.setSixMonthIncome(sixMonthIncome);
        //近1年
        String oneYearIncome = mainContent.css("dl.dataItem01 > dd:nth-child(4) > span.ui-font-middle.ui-color-red.ui-num","text").toString();
        if(null == oneYearIncome || oneYearIncome.length() == 0) {
            oneYearIncome = mainContent.css("dl.dataItem01 > dd:nth-child(4) > span.ui-font-middle.ui-color-green.ui-num","text").toString();
        }
        fundAnalysise.setOneYearIncome(oneYearIncome);
        //近2年
        String twoYearIncome = otherContent.css("tr:nth-child(2) > td:nth-child(8) j> div","text").toString();
        fundAnalysise.setTwoYearIncome(twoYearIncome);
        //近3年
        String threeYearIncome = mainContent.css("dl.dataItem02 > dd:nth-child(4) > span.ui-font-middle.ui-color-red.ui-num","text").toString();
        if(null == threeYearIncome || threeYearIncome.length() == 0) {
            threeYearIncome = mainContent.css("dl.dataItem02 > dd:nth-child(4) > span.ui-font-middle.ui-color-green.ui-num","text").toString();
        }
        fundAnalysise.setThreeYearIncome(threeYearIncome);

        Date date = new Date();
        fundAnalysise.setCreateTime(date);

        page.putField("fundAnalysis",fundAnalysise);
    }

    private Site site = Site.me()
            .setCharset("utf-8")
            .setTimeOut(10000)
            .setRetryTimes(3)
            .setRetrySleepTime(3000);
    @Override
    public Site getSite() {
        return this.site;
    }

//    @Scheduled(fixedDelay = 1000)
//    @Scheduled(cron = "0 00 23 ? * MON-FRI")
    public void fundAnalysiseProcessor() {
//        List<Fund> fundList = (List<Fund> )fundService.fundList().getData();
        List<String> fundList = Arrays.asList("003095","161121","001552",
                "502003","001064","161130","161125","005827","165520",
                "001616","163406","320007","004854","110003","100053",
                "161725","001344","110031","161033","160716","000248",
                "161028","000968","519671");
        String[] urls = new String[fundList.size()];

        if(null != fundList && fundList.size() > 0) {
            for (int i = 0; i < fundList.size(); i++) {
                urls[i] = "http://fund.eastmoney.com/"+fundList.get(i)+".html?spm=search";
            }
        } else {
            return;
        }
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String formatTime = simpleDateFormat.format(date);
        try {
            FileUtils.writeStringToFile(file,formatTime+"\r\n",true);
        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
            Spider.create(new FundAnalysiseProcessor())
                    .addUrl(urls)
                    .addPipeline(this.fundAnalysisePipeline)
                    .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100000)))
                    .thread(1)
                    .run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
